using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Cil.Ast;

public sealed class UnboxingExpression : SingleInstructionExpression
{
	public const int ValuePos = 0;
	public const int MaxNodes = 1;

	public UnboxingExpression(Context context, Instruction position, Expression exp_value)
		: base(context, position)
	{
		if(!(position.Operand as TypeReference).IsValueType)
		{
			throw new ArgumentException("val should be value type");
		}

		// base class
		Nodes = new FixedList<Expression>(MaxNodes);
		ReturnType = position.Operand as TypeReference;
		ReadsStack = 1;
		WritesStack = 1;
		Value = exp_value;
	}

	public Expression Value { get { return Nodes[ValuePos]; } set { Nodes[ValuePos] = value; value.ParentNode = this; } }

	public override string ToString()
	{
		return string.Format("(({1}){0})", Value, ReturnType);
	}
}

public static partial class IlAst
{
	public static UnboxingExpression Unboxing(Context context, Instruction position, Expression exp_value)
	{
		return new UnboxingExpression(context, position, exp_value);
	}
}